# -*- coding: utf-8 -*-
import sys
sys.path.append('..')
import threading
import commonlib
import traceback
import datetime
import time
import simplejson as json
import re
import math
from pymongo import Connection
from termcolor import cprint

logger = commonlib.getLogger('wlive.7m.cn')
MONGO_SERVER = '27.0.12.106'
#MONGO_SERVER = 'beta.mana.vn'
MONGO_PORT = 27017

class GetFeed(threading.Thread):
    
    def __init__(self, match):
        threading.Thread.__init__(self)
        threading.Thread.setName(self, "{0} vs {1}".format(match.get('hTeam', ''), match.get('vTeam', '')))
        self.__match = match
    
    def start(self):
        threading.Thread.start(self)
        logger.info('start thread to feed the match between: {0}'.format(self.getName()))
    
    def arraydict2dict(self, arrdict, key):
        dict = {}
        for item in arrdict:
            id = item[key]
            dict[id] = item
        return dict
    
    def connection(self):
        connection = Connection(MONGO_SERVER, MONGO_PORT)
        return connection
    
    def eventType(self, event):
        name = event['name']
        if name == "substitution": return ["subs", '']
        elif name == "booking": return ["yellow", event['pid']]
        elif name == "dismissal" and event['reason'] == "Second Bookable Offence": return ["yellow2", event['pid']]
        elif name == "dismissal" and event['reason'] != "Second Bookable Offence": return ["red", event['pid']]
        elif name == "goal" and event['outcome'] in ['C', 'P']: return ["goal", event['pid']]
        elif name == "goal" and event['outcome'] != 'C': return ["owngoal", event['pid']]
        return ["", ""]
    
    def getScore(self, events):
        score = {}
        s = {'h': 0, 'a': 0}
        score[0] = "0-0"
        for event in events:
            if event['name'] == 'goal':
                if event['outcome'] == 'C':
                    if event['home'] == 1:
                        s['h'] += 1
                    else:
                        s['a'] += 1
                else:
                    if event['home'] == 1:
                        s['a'] += 1
                    else:
                        s['h'] += 1
                score[event['tf']] = "{0}-{1}".format(s['h'], s['a'])
        return score
    
    def getEvent(self, events):
        data = {}
        for event in events:
            name, pid = self.eventType(event)
            if name != '':
                data[event['tf']] = {'name': name, 'pid': pid}
        return data
    
    def getScoreWithtf(self, tf, score, top=0):
        j = 0
        for i in sorted(score, key=score.get):
            if top == 0:
                if tf == i: return score[i]
                if tf < i: return score[j]
            j = i
        return score[j]
    
    def yard2meter(self, msg):
        try:
            if re.search(r'(\d+) yards', msg):
                msg = re.sub(r'(\d+) yards', lambda m: "{0} mét".format(int(math.ceil(int(m.group(1))*0.9144))), msg)
        finally:
            return msg
    
    def fixTranslator(self, msg):
        msg = commonlib.encodeUTF8Str(msg)
        msg = msg.replace('đá phạt ném biên ở câu môn đối phương', 'ném biên lên')
        msg = msg.replace('đá phạt ném biên từ cầu môn bên mình', 'ném biên về')
        msg = msg.replace('đá phạt ném biên', 'ném biên')
        msg = msg.replace('vị phạm', 'vi phạm')
        msg = msg.replace("vôlê", "vô-lê")
        msg = msg.replace("câu môn", "cầu môn")
        msg = msg.replace("phạm lỗi cho", "phạm lỗi với")
        msg = msg.replace("cột dọc gần nhất", "cột dọc ở gần")
        msg = msg.replace("cột dọc xa hơn", "cột dọc ở xa")
        msg = msg.replace("xà ngang trên", "xà ngang")
        msg = msg.replace("(chiến thuật)", "(thay người chiến thuật)")
        msg = msg.replace("vi phạm lỗi chơi xấu", "do phạm lỗi chơi xấu")
        msg = msg.replace("bay ra biên ngoài", "bay ra ngoài biên")
        msg = self.yard2meter(msg)
        return msg
    
    def second2ms(self, num, div=60):
        if num == -1: return ''
        a = int(num / div)
        b = num % div
        if b < 10: b = "0{0}".format(b)
        return "{0}:{1}".format(a, b)
    
    def getTeam(self, feed):
        teams = {'home': [], 'away': []}
        if not feed.has_key('lineup'): return teams
        players = self.arraydict2dict(feed['lineup'], 'tid')
        for pl in players.values():
            pos = {'Striker': 'Tiền đạo', 'Midfielder': 'Tiền vệ', 'Defender': 'Hậu vệ', 'Goal Keeper': 'Thủ môn'}
            pl['pos'] = pos.get(pl['pos'], '')
            if pl['home']:
                teams['home'].append(pl)
            else:
                teams['away'].append(pl)
        return teams
    
    def getLiveFeed(self, feed):
        data = []
        try:
            if not feed.has_key('event'): logger.info('match ({0} vs {1}) chưa có dữ liệu chi tiết'.format(feed['hTeam'], feed['vTeam'])); return
            events = self.getEvent(feed['event'])
            score = self.getScore(feed['event'])
            players = self.arraydict2dict(feed['lineup'], 'tid')
            jj = 0
            for line in feed['textFeed']:
                tf = line['tf']
                if tf > 0: jj = tf
                textfeed = self.fixTranslator(line['msg'])
                mtime = self.second2ms(line['time'])
                ievent = events.get(tf, '')
                if ievent != '':
                    if ievent['pid'] != '': 
                        aplayer = players.get(ievent['pid'], '')
                        ievent['pid'] = aplayer['name'] if aplayer != '' else ''
                sc = self.getScoreWithtf(jj, score)
                if textfeed == 'Kết quả': textfeed += ": " + sc
                data.append({
                    'time': mtime,
                    'score': sc,
                    'event': ievent['name'] if ievent != '' else '',
                    'player': ievent['pid'] if ievent != '' else '',
                    'text': textfeed
                })
        except:
            logger.error(traceback.format_exc())
        finally:
            return data
    
    def run(self):
        logger.debug('run thread to feed the match between: {0}'.format(self.getName()))
        match = self.__match
        url = 'http://wlive.7m.cn/livedata/vn/{0}.js?nocache={1}'.format(match['id'], time.time())
        isFinished = False
        while isFinished == False:
            try:
                html = commonlib.getHTML(url, max_retries=5, delay=2, headers={'X-Requested-With': 'XMLHttpRequest'})
                feed = json.loads(html)
                now = datetime.datetime.utcnow()
                if feed and len(feed)>0:
                    matchTime =  match['date']
                    m_status = ''
                    logger.info('match "{0}" - status: {1}'.format(self.getName(), feed['status']))
                    if feed['status'] not in ['', 'MC']: m_status = 'living'
                    if feed['status'] == 'MC': isFinished = True; m_status = 'finished'
                    data = self.getLiveFeed(feed)
                    doihinh = self.getTeam(feed)
                    connection = self.connection()
                    db = connection['bongda']
                    collection = db['live']
                    sdata = {'_id': feed['oid'],
                        'homeTeam': feed['hTeam'],
                        'awayTeam': feed['vTeam'],
                        'score': '{0}-{1}'.format(feed['hPoint'], feed['vPoint']),
                        'time': match['date'],
                        'crtime': data[len(data)-1]['time'] if len(data) > 0 else '',
                        'dategmt7': match['dategmt7'].strftime("%d/%m/%Y"),
                        'dateutc': matchTime.strftime("%d/%m/%Y"),
                        'data': data,
                        'eventId': len(data) -1 if len(data) > 0 else 0,
                        'doihinh': doihinh,
                        'status': m_status,
                        'liveId': match['id'],
                        'giaidau': match['giaidau']
                        }
                    collection.save(sdata)
                    connection.end_request()
                if (now.hour < matchTime.hour - 1) or (now.hour > matchTime.hour + 3): break
                if not isFinished: logger.debug('thread feed match between: {0} still running'.format(self.getName()))
                else: logger.info('match "{0}" finished'.format(self.getName()))
                if feed['status'] != 'MC': 
                  if feed['status'] != 'HT': time.sleep(30)
                  else: time.sleep(300)
            except:
                logger.error(traceback.format_exc()); break
        logger.debug('finished thread to feed the match between: {0}'.format(self.getName()))
        
